// 页面导出为 pdf 格式
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const htmltopdf  = {
  //   getpdf(title,url) {
  //   html2canvas(document.querySelector('#content-to-print'), {
  //     allowTaint: false,
  //     taintTest: false,
  //     logging: false,
  //     useCORS: true,
  //     dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的 dpi 提高四倍
  //     scale: 4 // 按比例增加分辨率
  //   }).then(canvas => {
  //     var pdf = new jsPDF('p','mm','a4'); // a4 纸，纵向
  //     var ctx = canvas.getContext('2d'),
  //       a4w = 190, a4h = 277; // a4 大小，210mmx297mm，四边各保留 10mm 的边距，显示区域 190x277
  //     var imgHeight = Math.floor(a4h * canvas.width / a4w), // 按 a4 显示比例换算一页图像的像素高度
  //     renderHeight = 0;

  //     while (renderHeight < canvas.height) {
  //       var page = document.createElement("canvas");
  //       page.width = canvas.width;
  //       page.height = Math.min(imgHeight, canvas.height - renderHeight); // 可能内容不足一页

  //       // 用 getImageData 剪裁指定区域，并画到前面创建的 canvas 对象中
  //       page.getContext('2d').putImageData(ctx.getImageData(0, renderHeight, canvas.width, Math.min(imgHeight, canvas.height - renderHeight)), 0, 0);

  //       pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'jpeg', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)); // 添加图像到页面，保留 10mm 边距

  //       renderHeight += imgHeight;
  //       if (renderHeight < canvas.height) {
  //         pdf.addPage(); // 如果后面还有内容，添加一个空页
  //       }
  //     }

  //     // 保存文件
  //     pdf.save(title + '.pdf');
  //   })
  // }
  getpdf(title, id) { 
    let printdom = document.getElementById(id);
    // 根据 A4 的宽高计算 DOM 页面一页应该对应的高度
    let pageheight = printdom.offsetWidth / 592.28 * 880; 
    // 将所有不允许被截断的元素进行处理
    // let wholeNodes = document.querySelectorAll('p,table,.page-break'); 
    let wholeNodes = document.querySelectorAll('p,.table-no-pagination,.page-break'); 
    for (let i = 0; i < wholeNodes.length; i++) {
      // 1. 判断当前的不可分页元素是否在两页显示
      const topPagenum = Math.ceil((wholeNodes[i].offsetTop) / pageheight);
      const bottomPagenum = Math.ceil((wholeNodes[i].offsetTop + wholeNodes[i].offsetHeight) / pageheight);
      if (topPagenum!== bottomPagenum) { 
      debugger
        // 说明该 DOM 会被截断
        // 2. 插入空白块使被截断元素下移
        let divParent = wholeNodes[i].parentNode;
        let newBlock = document.createElement('div');
        newBlock.className = 'emptydiv'; 
        newBlock.style.background = '#fff'; 
        // 3. 计算插入空白块的高度，可以适当流出空间使得内容不太靠边，根据自己需求而定
        let _h = topPagenum * pageheight - wholeNodes[i].offsetTop;
        newBlock.style.height = _h + 24 + 'px'; 
        divParent.insertBefore(newBlock, wholeNodes[i]); 
      }
    }
    // 以上完成 DOM 层面的分页，可以转为图片进一步处理了
    html2canvas(printdom, { height: printdom.offsetHeight, width: printdom.offsetWidth, scrollX: -window.pageXOffset, allowTaint: true ,useCORS: true,dpi: window.devicePixelRatio * 4,scale: 4}).then(canvas => { 
      // DOM 已经转换为 canvas 对象，可以将插入的空白块删除了
      let emptyDivs = document.querySelectorAll('.emptydiv'); 
      for (let i = 0; i < emptyDivs.length; i++) {
        emptyDivs[i].parentNode.removeChild(emptyDivs[i]); 
      }
      // 后续生成 PDF 的代码保持不变...
      var pdf = new jsPDF('p','mm','a4'); 
      var ctx = canvas.getContext('2d'),
          a4w = 190,
          a4h = 277, 
      imgHeight = Math.floor(a4h * canvas.width / a4w), 
      renderHeight = 0;

      while (renderHeight < canvas.height) { 
        var page = document.createElement("canvas");
        page.width = canvas.width;
        page.height = Math.min(imgHeight, canvas.height - renderHeight); 

        page.getContext('2d').putImageData(ctx.getImageData(0, renderHeight, canvas.width, Math.min(imgHeight, canvas.height - renderHeight)), 0, 0);

        pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'jpeg', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)); 

        renderHeight += imgHeight;
        if (renderHeight < canvas.height) { 
          pdf.addPage(); 
        }
      }

      pdf.save(title + '.pdf'); 
    });
  },

  getPdf(id) { 
    return new Promise((resolve, reject) => {
      let printdom = document.getElementById(id);
      printdom.style.width = ' 707px';
      // 根据 A4 的宽高计算 DOM 页面一页应该对应的高度
      let pageheight = printdom.offsetWidth / 592.28 * 880; 
      // 将所有不允许被截断的元素进行处理
      let wholeNodes = document.querySelectorAll('p,.table-no-pagination,.page-break'); 
      for (let i = 0; i < wholeNodes.length; i++) {
        // 1. 判断当前的不可分页元素是否在两页显示
        const topPagenum = Math.ceil((wholeNodes[i].offsetTop) / pageheight);
        const bottomPagenum = Math.ceil((wholeNodes[i].offsetTop + wholeNodes[i].offsetHeight) / pageheight);
        if (topPagenum!== bottomPagenum) { 
          // 说明该 DOM 会被截断
          // 2. 插入空白块使被截断元素下移
          let divParent = wholeNodes[i].parentNode;
          let newBlock = document.createElement('div');
          newBlock.className = 'emptydiv'; 
          newBlock.style.background = '#fff'; 
          // 3. 计算插入空白块的高度，可以适当流出空间使得内容不太靠边，根据自己需求而定
          let _h = topPagenum * pageheight - wholeNodes[i].offsetTop;
          newBlock.style.height = _h + 24 + 'px'; 
          divParent.insertBefore(newBlock, wholeNodes[i]); 
        }
      }
      // 以上完成 DOM 层面的分页，可以转为图片进一步处理了
      html2canvas(printdom, { height: printdom.offsetHeight, width: printdom.offsetWidth, scrollX: -window.pageXOffset, allowTaint: true ,useCORS: true,dpi: window.devicePixelRatio * 4,scale: 4}).then(canvas => { 
        // DOM 已经转换为 canvas 对象，可以将插入的空白块删除了
        let emptyDivs = document.querySelectorAll('.emptydiv'); 
        for (let i = 0; i < emptyDivs.length; i++) {
          emptyDivs[i].parentNode.removeChild(emptyDivs[i]); 
        }
        // 后续生成 PDF 的代码保持不变...
        var pdf = new jsPDF('p','mm','a4'); 
        var ctx = canvas.getContext('2d'),
            a4w = 190,
            a4h = 277, 
        imgHeight = Math.floor(a4h * canvas.width / a4w), 
        renderHeight = 0;
  
        while (renderHeight < canvas.height) { 
          var page = document.createElement("canvas");
          page.width = canvas.width;
          page.height = Math.min(imgHeight, canvas.height - renderHeight); 
  
          page.getContext('2d').putImageData(ctx.getImageData(0, renderHeight, canvas.width, Math.min(imgHeight, canvas.height - renderHeight)), 0, 0);
  
          pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'jpeg', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)); 
  
          renderHeight += imgHeight;
          if (renderHeight < canvas.height) { 
            pdf.addPage(); 
          }
        }
        printdom.style.width = ' initial';
        resolve(pdf);
        // pdf.save(title + '.pdf'); 
      });
    });
    
  }

  
};

export default htmltopdf;